import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const downloadFile = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
  
  const doDownload = () => {
    const task = uni.downloadFile({
      url: config.baseUrl || baseUrl + config.url,
      header: config.header || {},
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath);
        } else {
          retry(`HTTP ${res.statusCode}`);
        }
      },
      fail: (err) => retry(err.errMsg),
    });
  
    if (typeof onProgress === 'function') {
      task.onProgressUpdate((progress) => {
        onProgress(progress.progress);
      });
    }
  };

  
  doDownload();
  })
}

export default downloadFile
